package com.inhim.pjhim.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.VideoView;

import com.inhim.pjhim.R;
import com.inhim.pjhim.activity.VideoActivity;
import com.inhim.pjhim.utils.UIUtils;

import java.math.BigDecimal;


public class VideoFloatView {
    private static WindowManager mWindowManager;
    private static View mShowView;
    private WindowManager.LayoutParams mFloatParams;
    private final static double ASPECT_RATIO=0.6;
    private static Handler mMainHandler=new Handler();
    private static ConstraintLayout background_layout;
    private final static int HIDE_VIEW_TIME=1000;
    private int mReaderId;
    public void initFloatView(String urls, Context context, boolean playing, int duration, int readerId) {
        mReaderId=readerId;
        View view = View.inflate(context, R.layout.view_floating_window, null);
        // 设置视频封面
        //final ImageView mThumb = (ImageView) view.findViewById(R.id.thumb_floating_view);
        //Glide.with(this).load(R.drawable.thumb).into(mThumb);
        // 悬浮窗关闭
        view.findViewById(R.id.close_floating_view).setOnClickListener(v -> dismiss());
        // 返回前台页面
        //view.findViewById(R.id.back_floating_view).setOnClickListener(v -> mFloatingWindow.setTopApp(VideoActivity.this));
        final VideoView videoView = view.findViewById(R.id.video_view);
        ProgressBar seekBar=view.findViewById(R.id.bottom_seek_progress);
        //视频内容设置
        //videoView.setVideoPath("https://stream7.iqilu.com/10339/article/202002/18/2fca1c77730e54c7b500573c2437003f.mp4");
        videoView.setVideoPath(urls);
        // 视频准备完毕，隐藏正在加载封面，显示视频
        //videoView.setOnPreparedListener(mp -> mThumb.setVisibility(View.GONE));
        // 循环播放
        videoView.setOnCompletionListener(mp -> videoView.start());
        ImageView iv_start=view.findViewById(R.id.iv_start);
        iv_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(videoView.isPlaying()){
                    videoView.pause();
                    iv_start.setImageResource(R.drawable.jc_play_normal);
                }else{
                    videoView.start();
                    iv_start.setImageResource(R.drawable.jc_pause_normal);
                    updataProgress(videoView,seekBar);
                }
            }
        });
        // 开始播放视频
        if(playing){
            videoView.start();
            iv_start.setImageResource(R.drawable.jc_pause_normal);
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    updataProgress(videoView,seekBar);
                }
            },6000);
        }
        videoView.seekTo(duration);
        ImageView iv_speed = view.findViewById(fm.jiecao.jcvideoplayer_lib.R.id.iv_speed);
        ImageView iv_reteat = view.findViewById(fm.jiecao.jcvideoplayer_lib.R.id.iv_retreat);
        iv_speed.setOnClickListener(v -> {
            setSpeedReteat(videoView,15000,seekBar);
        });
        iv_reteat.setOnClickListener(v -> {
            setSpeedReteat(videoView,-15000,seekBar);
        });
        ImageView fullscreen=view.findViewById(R.id.fullscreen);
        fullscreen.setOnClickListener(v -> setTopApp(context,videoView));
        background_layout=view.findViewById(R.id.background_layout);
        showFloatingWindowView(context,view);
    }
    private Handler mainHandler=new Handler();
   private Thread mThread;
    private void updataProgress(final VideoView videoView, ProgressBar seekBar){
        mThread=new Thread() {
            @Override
            public void run() {
                try {
                    while (videoView.isPlaying()) {
                        // 如果正在播放，没0.5.毫秒更新一次进度条
                        int current = videoView.getCurrentPosition()*100/videoView.getDuration();
                        seekBar.setProgress(current);
                        Log.d("zhiqiang","===========current:"+current);
                        Log.d("zhiqiang","getCurrentPosition:"+videoView.getCurrentPosition());
                        Log.d("zhiqiang","getDuration:"+videoView.getDuration());
                        sleep(500);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        mThread.start();
    }

    private void setSpeedReteat(final VideoView videoView,int time,ProgressBar seekBar) {
        Log.d("zhiqiang","time111----:"+time);
        time = seekBar.getProgress() * videoView.getDuration() / 100 + time;
        Log.d("zhiqiang","time----:"+time);
        Log.d("zhiqiang","getProgress:"+seekBar.getProgress() );
        Log.d("zhiqiang","getDuration:"+videoView.getDuration() );
        videoView.seekTo(time);
    }

    public void showFloatingWindowView(Context context, View view) {
        // 悬浮窗显示视图
        mShowView = view;
        // 获取系统窗口管理服务
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        // 悬浮窗口参数设置及返回
        mFloatParams = getParams(context);
        // 设置窗口触摸移动事件
        mShowView.setOnTouchListener(new FloatViewMoveListener());
        // 悬浮窗生成
        mWindowManager.addView(mShowView, mFloatParams);
    }

    private WindowManager.LayoutParams getParams(Context context) {
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        //设置悬浮窗口类型
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        //设置悬浮窗口属性
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        //设置悬浮窗口透明
        layoutParams.format = PixelFormat.TRANSLUCENT;
        //设置悬浮窗口长宽数据
        int width1;
        if(UIUtils.getAppWidth(context)>UIUtils.getAppHeight(context)){
            width1=UIUtils.getAppHeight(context);
        }else{
            width1=UIUtils.getAppWidth(context);
        }
        int width=width1*4/5;
        layoutParams.width = width;
        layoutParams.height = (int) (width*ASPECT_RATIO);
        //设置悬浮窗显示位置
        layoutParams.gravity = Gravity.START | Gravity.TOP;
        layoutParams.x = 100;
        layoutParams.y = 100;
        return layoutParams;
    }

    private class FloatViewMoveListener implements View.OnTouchListener {

        //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
        private int mTouchStartX;
        private int mTouchStartY;
        //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
        private int mStartX, mStartY;
        //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
        private boolean isMove;

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            int action = motionEvent.getAction();
            int x = (int) motionEvent.getX();
            int y = (int) motionEvent.getY();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    isMove = false;
                    mTouchStartX = (int) motionEvent.getRawX();
                    mTouchStartY = (int) motionEvent.getRawY();
                    mStartX = x;
                    mStartY = y;
                    background_layout.setVisibility(View.VISIBLE);
                    mMainHandler.removeCallbacks(showBackgroundLayout);
                    mMainHandler.postDelayed(showBackgroundLayout,HIDE_VIEW_TIME);
                    break;
                case MotionEvent.ACTION_MOVE:
                    int mTouchCurrentX = (int) motionEvent.getRawX();
                    int mTouchCurrentY = (int) motionEvent.getRawY();
                    mFloatParams.x += mTouchCurrentX - mTouchStartX;
                    mFloatParams.y += mTouchCurrentY - mTouchStartY;
                    mWindowManager.updateViewLayout(mShowView, mFloatParams);
                    mTouchStartX = mTouchCurrentX;
                    mTouchStartY = mTouchCurrentY;
                    float deltaX = x - mStartX;
                    float deltaY = y - mStartY;
                    if (Math.abs(deltaX) >= 5 || Math.abs(deltaY) >= 5) {
                        isMove = true;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                default:
                    break;
            }
            //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
            return isMove;
        }
    }

    private static Runnable showBackgroundLayout= () -> {
        background_layout.setVisibility(View.GONE);
    };

    public static void dismiss() {
        if (mWindowManager != null && mShowView != null) {
            mMainHandler.removeCallbacks(showBackgroundLayout);
            mWindowManager.removeView(mShowView);
        }
    }

    @SuppressLint("MissingPermission")
    public void setTopApp(Context context, VideoView videoView) {
        mMainHandler.removeCallbacksAndMessages(null);
        mMainHandler.postDelayed(() -> {
            dismiss();
            try{
                Intent intent = new Intent ("com.inhim.pjhim.activity.VideoActivity");
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                intent.putExtra("ReaderId", mReaderId);
                intent.putExtra("isPlaying", videoView.isPlaying());
                intent.putExtra("Duration", videoView.getCurrentPosition());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction("com.inhim.pjhim.PLAYVIDEO");
                context.startActivity(intent);
            }catch (Exception e){
                e.printStackTrace();
            }
        },500);

        //获取ActivityManager
        /*ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //获得当前运行的task(任务)
        List<ActivityManager.RunningTaskInfo> taskInfoList = null;
        if (activityManager != null) {
            taskInfoList = activityManager.getRunningTasks(100);
        }
        if (taskInfoList != null) {
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                //找到本应用的 task，并将它切换到前台
                if (taskInfo.topActivity != null && taskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
                    activityManager.moveTaskToFront(taskInfo.id, 0);
                    break;
                }
            }
        }*/
    }
}
